package com.runtime.hongyunmanage.controller;

import com.runtime.hongyunmanage.bean.Categories;
import com.runtime.hongyunmanage.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Value("${category.upload.path:static/image/categoryimage/}")
    private String categoryUploadPath;

    @PostMapping("/add")
    public Result addCategory(@RequestBody Categories categories) {

        // 调用服务层方法，处理业务逻辑
        boolean flag = categoryService.addCategory(categories);

        // 返回结果
        Integer code = flag ? Code.SAVE_OK : Code.SAVE_ERR;
        String msg = flag ? "增加商品目录成功" : "增加商品目录失败";
        return new Result(code, flag, msg);
    }


    @GetMapping("/{categoryId}")
    public Result getCategory(@PathVariable Long categoryId) {
        Categories category = categoryService.getCategoryById(categoryId);
        Integer code = category != null ? Code.GET_OK : Code.GET_ERR;
        String msg = category != null ? "查询商品目录成功" : "查询商品目录失败";
        return new Result(code, category, msg);
    }

    @GetMapping
    public Result getCategoryList(@RequestParam(required = false) Long parentId,
                                  @RequestParam(required = false) String keyword) {
        List<Categories> list = categoryService.getCategoryList(parentId, keyword);
        Integer code = null != list && list.size() > 0 ? Code.GET_OK : Code.GET_ERR;
        String msg = null != list && list.size() > 0 ? "查询商品目录列表成功" : "查询商品目录列表失败";
        return new Result(code, list, msg);
    }

    @PutMapping
    public Result updateCategory(@RequestBody Categories categories) {
        boolean flag = categoryService.updateCategory(categories);
        Integer code = flag ? Code.UPDATE_OK : Code.UPDATE_ERR;
        String msg = flag ? "修改商品目录成功" : "修改商品目录失败";
        return new Result(code, flag, msg);
    }

    @DeleteMapping("/{categoryId}")
    public Result deleteCategory(@PathVariable Long categoryId) {
        boolean flag = categoryService.deleteCategory(categoryId);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        String msg = flag ? "删除商品目录成功" : "删除商品目录失败";
        return new Result(code, flag, msg);
    }

    @DeleteMapping("/deleteimage/{fileName}")
    public Result deleteCategoryImage(@PathVariable String fileName,
                                      @RequestParam(required = false) Long categoryId) {
        try {
            // 1. 删除物理文件（原有逻辑）
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:/" + categoryUploadPath);
            File dir = resource.getFile();
            File fileToDelete = new File(dir, fileName);

            if (!fileToDelete.exists()) {
                return new Result(Code.DELETE_ERR, null, "文件不存在");
            }

            boolean success = fileToDelete.delete();
            if (!success) {
                return new Result(Code.DELETE_ERR, null, "删除失败");
            }

            // 2. 若传递了 categoryId，更新数据库中的 imageUrl 字段
            if (categoryId != null) {
                Categories category = categoryService.getById(categoryId);
                if (category != null) {
                    category.setImageUrl(null);
                    categoryService.deleteCategoryimage(category);
                }
            }

            return new Result(Code.DELETE_OK, null, "删除成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR, null, "删除过程中发生错误");
        }
    }
}